<template>
  <view class="merchant-page">
    <!-- 商家头部 -->
    <MerchantHeader :merchantInfo="merchantInfo" />

    <!-- Tab导航 -->
    <TabBar 
      :tabs="tabs" 
      :currentTab="currentTab" 
      @change="currentTab = $event" 
    />

    <!-- Tab内容 -->
    <view class="tab-content">
      <!-- 点菜Tab -->
      <view v-show="currentTab === 0" class="menu-container">
        <CategoryList
          :categories="categories"
          :currentIndex="currentCategory"
          :cartItems="cartItems"
          @select="selectCategory"
        />
        
        <ProductList
          :categories="categories"
          :cartItems="cartItems"
          @add-to-cart="handleAddToCart"
          @increase="increaseItem"
          @decrease="decreaseItem"
        />
      </view>

      <!-- 评价Tab -->
      <ReviewList
        v-show="currentTab === 1"
        :reviews="reviews"
        :stats="reviewStats"
      />

      <!-- 商家Tab -->
      <MerchantInfo
        v-show="currentTab === 2"
        :merchantInfo="merchantInfo"
        @call-phone="callPhone"
      />
    </view>

    <!-- 购物车栏 -->
    <CartBar
      v-show="currentTab === 0"
      :totalCount="totalCount"
      :totalPrice="totalPrice"
      :deliveryFee="merchantInfo.deliveryFee"
      :minPrice="merchantInfo.minPrice"
      @toggle-cart="toggleCart"
      @checkout="goToConfirm"
    />

    <!-- 购物车弹窗 -->
    <CartModal
      :visible="showCart"
      :cartItems="cartItems"
      @close="showCart = false"
      @clear="clearCart"
      @increase="increaseItem"
      @decrease="decreaseItem"
    />

    <!-- 商品规格选择弹窗 -->
    <ProductSpecsModal
      v-if="showSpecsModal"
      :visible="showSpecsModal"
      :product="currentProduct"
      @close="showSpecsModal = false"
      @confirm="handleSpecsConfirm"
    />
  </view>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { useUserStore } from '@/store/modules/user';
import { useMerchantData } from './composables/useMerchantData';
import { useCart } from './composables/useCart';
import { useReviews } from './composables/useReviews';

// 导入组件
import MerchantHeader from './components/MerchantHeader.vue';
import TabBar from './components/TabBar.vue';
import CategoryList from './components/CategoryList.vue';
import ProductList from './components/ProductList.vue';
import ReviewList from './components/ReviewList.vue';
import MerchantInfo from './components/MerchantInfo.vue';
import CartBar from './components/CartBar.vue';
import CartModal from './components/CartModal.vue';
import ProductSpecsModal from './modals/ProductSpecsModal.vue';

const userStore = useUserStore();

// Tab配置
const tabs = ['点菜', '评价', '商家'];
const currentTab = ref(0);

// 使用组合式函数
const { 
  merchantInfo, 
  categories, 
  currentCategory, 
  loadMerchantData, 
  selectCategory,
  checkProductSpecs 
} = useMerchantData();

const { 
  cartItems, 
  showCart, 
  totalCount, 
  totalPrice, 
  addToCart,
  increaseItem,
  decreaseItem,
  getProductCount,
  toggleCart,
  clearCart 
} = useCart();

const { reviews, reviewStats, loadReviews } = useReviews();

// 规格选择
const showSpecsModal = ref(false);
const currentProduct = ref<any>(null);

// 页面加载
onLoad(async (options: any) => {
  if (options.id) {
    const merchantId = Number(options.id);
    await Promise.all([
      loadMerchantData(merchantId),
      loadReviews(merchantId, 4.8)
    ]);
  }
});

// 处理添加到购物车
const handleAddToCart = async (product: any) => {
  const hasSpecs = await checkProductSpecs(product.id);
  
  if (hasSpecs) {
    // 显示规格选择弹窗
    currentProduct.value = product;
    showSpecsModal.value = true;
  } else {
    // 直接加入购物车
    addToCart(product);
  }
};

// 规格确认
const handleSpecsConfirm = (data: any) => {
  const cartProduct = {
    id: data.product.id,
    name: data.product.name,
    price: data.price,      // 使用计算后的价格（包含额外费用）
    image: data.product.image,
    specs: data.specs
  };
  
  // 根据count批量添加
  for (let i = 0; i < data.count; i++) {
    addToCart(cartProduct, data.specs);
  }
  
  showSpecsModal.value = false;
  currentProduct.value = null;
};

// 拨打电话
const callPhone = () => {
  if (merchantInfo.value.phone) {
    uni.makePhoneCall({ phoneNumber: merchantInfo.value.phone });
  }
};

// 去结算
const goToConfirm = () => {
  if (totalPrice.value < merchantInfo.value.minPrice) {
    uni.showToast({
      title: `还差¥${(merchantInfo.value.minPrice - totalPrice.value).toFixed(1)}起送`,
      icon: 'none'
    });
    return;
  }
  
  if (!userStore.hasLogin) {
    uni.showModal({
      title: '提示',
      content: '请先登录',
      success: (res) => {
        if (res.confirm) {
          uni.navigateTo({ url: '/pages/login/login' });
        }
      }
    });
    return;
  }
  
  uni.navigateTo({
    url: `/pages/order/confirm/confirm?merchantId=${merchantInfo.value.id}&cartData=${encodeURIComponent(JSON.stringify({
      items: cartItems.value,
      merchantName: merchantInfo.value.name,
      deliveryFee: merchantInfo.value.deliveryFee,
      deliveryTime: merchantInfo.value.deliveryTime
    }))}`
  });
};
</script>

<style scoped>
.merchant-page {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 120rpx;
}

.tab-content {
  height: calc(100vh - 580rpx);
}

.menu-container {
  display: flex;
  height: 100%;
}
</style>